package com.ehsunbehravesh.service.security.service;

import com.ehsunbehravesh.service.security.ejb.password.CharacterSet;
import com.ehsunbehravesh.service.security.ejb.password.PasswordLocalBusiness;
import com.ehsunbehravesh.service.security.service.jaxb.BaseResult;
import com.ehsunbehravesh.service.security.service.jaxb.PasswordGenerateResponse;
import com.ehsunbehravesh.service.security.service.jaxb.PasswordMeterRequest;
import com.ehsunbehravesh.service.security.service.jaxb.PasswordMeterResponse;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 *
 * @author ehsun7b
 */
@Stateless
@LocalBean
@Path("password")
public class PasswordService {

  @EJB
  PasswordLocalBusiness passwordBusiness;

  @GET
  @Path("generate/{chars}/{minLength}/{maxLength}")
  @Produces(MediaType.APPLICATION_JSON)
  public PasswordGenerateResponse generatePassword(@PathParam("chars") String chars,
          @PathParam("minLength") int minLength,
          @PathParam("maxLength") int maxLength) {

    PasswordGenerateResponse result = new PasswordGenerateResponse();

    try {
      List<CharacterSet> charSets = new ArrayList<CharacterSet>();

      String[] charsParts = chars.split("&");

      for (String charsPart : charsParts) {
        CharacterSet characterSet = CharacterSet.getFromString(charsPart);
        charSets.add(characterSet);
      }

      String password = passwordBusiness.generatePassword(charSets, minLength, maxLength);
      result.setPassword(password);
      result.setStatus(BaseResult.Status.SUCCESS);
    } catch (Exception ex) {
      result.setStatus(BaseResult.Status.FAILURE);
      result.setMessage(ex.getMessage());
    }

    return result;
  }
  
  @POST
  @Path("meter")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public PasswordMeterResponse meterPassword(final PasswordMeterRequest request) {
    PasswordMeterResponse result = new PasswordMeterResponse();
    
    try {
      int point = passwordBusiness.passwordMeter(request.getPassword());
      result.setPoint(point);
      result.setStatus(BaseResult.Status.SUCCESS);
    } catch (Exception ex) {
      result.setStatus(BaseResult.Status.FAILURE);
      result.setMessage(ex.getMessage());
    }
    
    return result;
  }
}
